package com.pshcp.doctor.api;

import com.framework.base.PageList;
import com.framework.base.ResultBuilder;
import com.framework.base.ResultDTO;
import com.framework.exception.BizException;
import com.framework.logaop.Log;
import com.framework.logaop.LogSourceEnum;
import com.framework.logaop.LogTypeEnum;
import com.framework.thread.ReqComTool;
import com.framework.tool.CommonTool;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pshcp.doctor.ao.article.DoctorArticlePageAO;
import com.pshcp.doctor.ao.article.DoctorDraftArticlePageAO;
import com.pshcp.doctor.ao.article.PublishDoctorArticleAO;
import com.pshcp.doctor.ao.article.SaveDoctorArticleAO;
import com.pshcp.doctor.ao.common.CommonAO;
import com.pshcp.doctor.tool.DoctorArticleTool;
import com.pshcp.doctor.vo.article.DoctorArticleDetailVO;
import com.pshcp.doctor.vo.article.DoctorArticleVO;
import com.pshcp.domain.dto.DoctorArticleDTO;
import com.pshcp.domain.model.Doctor;
import com.pshcp.domain.model.DoctorArticle;
import com.pshcp.domain.model.DoctorArticleNotificationPatient;
import com.pshcp.domain.model.DoctorDept;
import com.pshcp.domain.model.DoctorPatient;
import com.pshcp.service.DoctorArticleNotificationPatientService;
import com.pshcp.service.DoctorArticleService;
import com.pshcp.service.DoctorDeptService;
import com.pshcp.service.DoctorPatientService;
import com.pshcp.service.DoctorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2022/11/3 15:10
 */
@Api(tags = {"医生端-文章接口"})
@Slf4j
@RestController
@RequestMapping("/api/doctor/article")
public class DoctorArticleAPI {

    @Autowired
    private DoctorArticleService doctorArticleService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private DoctorArticleNotificationPatientService doctorArticleNotificationPatientService;

    @Autowired
    private DoctorPatientService doctorPatientService;

    @Autowired
    private DoctorDeptService doctorDeptService;

    @ApiOperation("获取宣教文章列表(分页)")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "获取宣教文章列表(分页)")
    @PostMapping("getDoctorArticlePage")
    public ResultDTO<PageList<DoctorArticleVO>> getDoctorArticlePage(@RequestBody DoctorArticlePageAO doctorArticlePageAO) throws BizException {
        List<DoctorDept> doctorDepts = doctorDeptService.getDoctorDeptByDoctorId(ReqComTool.getUserId());
        List<Long> deptIds = doctorDepts.stream().map(DoctorDept::getDeptId).collect(Collectors.toList());
        DoctorArticleDTO doctorArticleDTO = DoctorArticleTool.buildGetDoctorArticlePage(deptIds, doctorArticlePageAO);
        PageList<DoctorArticle> pageList = doctorArticleService.list(doctorArticleDTO);
        PageList<DoctorArticleVO> page = CommonTool.buildPageList(pageList, DoctorArticleVO.class);
        buildDoctorInfo(page.getItems());
        return ResultBuilder.success(page);
    }

    @ApiOperation("获取宣教文章草稿列表(分页)")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "获取宣教文章草稿列表(分页)")
    @PostMapping("getDoctorDraftArticlePage")
    public ResultDTO<PageList<DoctorArticleVO>> getDoctorDraftArticlePage(@RequestBody DoctorDraftArticlePageAO doctorDraftArticlePageAO) throws BizException {
        DoctorArticleDTO doctorArticleDTO = DoctorArticleTool.buildGetDoctorDraftArticlePage(doctorDraftArticlePageAO);
        PageList<DoctorArticle> pageList = doctorArticleService.list(doctorArticleDTO);
        PageList<DoctorArticleVO> page = CommonTool.buildPageList(pageList, DoctorArticleVO.class);
        buildDoctorInfo(page.getItems());
        return ResultBuilder.success(page);
    }

    private void buildDoctorInfo(List<DoctorArticleVO> vos) {
        if (CollectionUtils.isEmpty(vos)) {
            return;
        }
        List<Long> doctorIds = vos.stream().map(v -> v.getDoctorId()).collect(Collectors.toList());
        List<Doctor> doctors = doctorService.findByIds(doctorIds);
        Map<Long, Doctor> doctorsMap = CollectionUtils.isEmpty(doctors) ? Maps.newHashMap() : doctors.stream().collect(Collectors.toMap(Doctor::getId, Function.identity(), (key1, key2) -> key2));
        vos.forEach(item -> {
            Doctor doctor = doctorsMap.get(item.getDoctorId());
            item.setDoctorName(doctor == null ? null : doctor.getName());
            item.setMediLevel(doctor == null ? null : doctor.getMediLevel());
        });
    }


    @ApiOperation("获取文章")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "获取文章")
    @PostMapping("getDoctorArticleById")
    public ResultDTO<DoctorArticleDetailVO> getDoctorArticleById(@RequestBody CommonAO commonAO) throws BizException {
        CommonTool.checkObj(commonAO.getId(), "90000006");
        DoctorArticle doctorArticle = doctorArticleService.findById(commonAO.getId());
        CommonTool.checkObj(doctorArticle, "90000007");
        Doctor doctor = doctorService.findById(doctorArticle.getDoctorId());
        DoctorArticleDetailVO doctorArticleDetailVO = CommonTool.copyProperties(doctorArticle, DoctorArticleDetailVO.class);
        doctorArticleDetailVO.setDoctorName(doctor==null?null:doctor.getName());
        List<DoctorArticleNotificationPatient> doctorArticleNotificationPatientList = doctorArticleNotificationPatientService.getDoctorArticleNotificationPatientList(doctorArticleDetailVO.getId());
        List<Long> patientIds = doctorArticleNotificationPatientList.stream().map(DoctorArticleNotificationPatient::getPatientId).collect(Collectors.toList());
        doctorArticleDetailVO.setPatientIds(patientIds);
        return ResultBuilder.success(doctorArticleDetailVO);
    }

    @ApiOperation("保存宣教文章")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "保存宣教文章")
    @PostMapping("saveDoctorArticle")
    public ResultDTO<Long> saveDoctorArticle(@RequestBody SaveDoctorArticleAO saveDoctorArticleAO) throws BizException {
        DoctorArticleTool.checkSaveDoctorArticle(saveDoctorArticleAO);
        Long doctorArticleId = null;
        if (saveDoctorArticleAO.getId() != null) {
            DoctorArticle doctorArticle = doctorArticleService.findById(saveDoctorArticleAO.getId());
            CommonTool.checkObj(doctorArticle, "90000007");
            Long userId = ReqComTool.getUserId();
            if (!userId.equals(doctorArticle.getDoctorId())) {
                return ResultBuilder.failure("10040008");
            }
            if (doctorArticle.getBizStatus() == 1) {
                return ResultBuilder.failure("10040009");
            }
            DoctorArticle updateDoctorArticle = DoctorArticleTool.buildSaveDoctorArticle(doctorArticle, saveDoctorArticleAO);
            doctorArticleService.update(updateDoctorArticle);
            doctorArticleId = updateDoctorArticle.getId();
        } else {
            Long userId = ReqComTool.getUserId();
            Doctor doctor = doctorService.findById(userId);
            DoctorDept doctorDept = doctorDeptService.getDoctorDeptByHisDeptId(doctor.getMainDeptId());
            DoctorArticle saveDoctorArticle = DoctorArticleTool.buildSaveDoctorArticle(doctorDept, saveDoctorArticleAO);
            doctorArticleId = doctorArticleService.insert(saveDoctorArticle);
        }
        List<DoctorArticleNotificationPatient> doctorArticleNotificationPatientList = doctorArticleNotificationPatientService.getDoctorArticleNotificationPatientList(doctorArticleId);
        List<DoctorPatient> doctorPatientList = doctorPatientService.getDoctorPatientList(ReqComTool.getUserId(), saveDoctorArticleAO.getPatientIds());
        List<DoctorArticleNotificationPatient> doctorArticleNotificationPatients = DoctorArticleTool.buildSaveDoctorArticleNotificationPatientList(0, doctorArticleId, doctorArticleNotificationPatientList, doctorPatientList);
        doctorArticleNotificationPatientService.batchSaveDoctorArticleNotificationPatient(doctorArticleNotificationPatients);
        return ResultBuilder.success(doctorArticleId);
    }

    @ApiOperation("发布宣教文章")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "发布宣教文章")
    @PostMapping("publishDoctorArticle")
    public ResultDTO<Long> publishDoctorArticle(@RequestBody PublishDoctorArticleAO publishDoctorArticleAO) throws BizException {
        DoctorArticleTool.checkPublishDoctorArticle(publishDoctorArticleAO);
        DoctorArticle doctorArticle = publishDoctorArticleAO.getId() == null ? null : doctorArticleService.findById(publishDoctorArticleAO.getId());
        Long doctorArticleId = null;
        if (publishDoctorArticleAO.getPublishType() == 0) {
            CommonTool.checkObj(doctorArticle, "90000007");
            DoctorArticle publishDoctorArticle = DoctorArticleTool.buildPublishDoctorArticle(doctorArticle);
            doctorArticleService.update(publishDoctorArticle);
            doctorArticleId = publishDoctorArticle.getId();
            List<DoctorArticleNotificationPatient> doctorArticleNotificationPatientList = doctorArticleNotificationPatientService.getDoctorArticleNotificationPatientList(doctorArticleId);
            List<DoctorArticleNotificationPatient> doctorArticleNotificationPatients = DoctorArticleTool.buildSaveDoctorArticleNotificationPatientList(doctorArticleNotificationPatientList);
            doctorArticleNotificationPatientService.batchSaveDoctorArticleNotificationPatient(doctorArticleNotificationPatients);
        } else {
            Doctor doctor = doctorArticle == null ? doctorService.findById(ReqComTool.getUserId()) : null;
            DoctorArticle publishDoctorArticle = DoctorArticleTool.buildPublishDoctorArticle(doctorArticle, publishDoctorArticleAO);
            doctorArticleId = publishDoctorArticle.getId();
            if (doctorArticle == null) {
                doctorArticleId = doctorArticleService.insert(publishDoctorArticle);
            } else {
                doctorArticleService.update(publishDoctorArticle);
            }
            List<DoctorArticleNotificationPatient> doctorArticleNotificationPatientList = doctorArticleNotificationPatientService.getDoctorArticleNotificationPatientList(doctorArticleId);
            List<Long> patientIdList = Lists.newArrayList();
            String patientIds = publishDoctorArticleAO.getPatientIds();
            if (!StringUtils.isBlank(patientIds)) {
                String[] patientIdArr = StringUtils.split(patientIds, ",");
                for (String patientId : patientIdArr) {
                    if (StringUtils.isBlank(patientId)) {
                        continue;
                    }
                    patientIdList.add(Long.valueOf(patientId));
                }
            }
            List<DoctorPatient> doctorPatientList = doctorPatientService.getDoctorPatientList(ReqComTool.getUserId(), patientIdList);
            List<DoctorArticleNotificationPatient> doctorArticleNotificationPatients = DoctorArticleTool.buildSaveDoctorArticleNotificationPatientList(1, doctorArticleId, doctorArticleNotificationPatientList, doctorPatientList);
            doctorArticleNotificationPatientService.batchSaveDoctorArticleNotificationPatient(doctorArticleNotificationPatients);
        }
        return ResultBuilder.success(doctorArticleId);
    }
}
